# -*- coding: utf-8 -*-
# 读取文件
import re
import requests
import os

source_file = './cnbc_files/cnbc.html'
file_save_path = './cnbc_files/files/'
file_access_path = './files/'

heads = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
}


# 01. 读取源文件
def read_file(source_file_param, save_path_param, access_path_param):
    with open(source_file, 'r', encoding='utf-8') as file:
        page_text = file.read()
        for line in file:
            # 处理每一行的内容
            line_str = line.strip()
            # print('line: ', line.strip())  # strip()方法用于删除每一行末尾的换行符
            if (line_str.startswith('src: url(')):
                # 需要更改的字体访问路径
                resourceUrl = line_str.split('src: url(')[1].split(') format("woff2")')[0]
                print('resourceUrl: ', resourceUrl)
                file_name = line_str.split('/')[-1]
                save_path_param = save_path_param + file_name
                access_path_param = access_path_param + file_name
                # 下载字体文件
                write_woff_file(save_path_param, resourceUrl)
                page_text = page_text.replace(resourceUrl, access_path_param)
    file.close()
    return page_text


# 02. 下载字体文件
def write_woff_file(file_param, url_param):
    result = requests.get(url=url_param, headers=heads)
    # 判断文件是否存在
    if (os.path.exists(file_param)):
        pass
    else:
        with open(file_param, mode='w', encoding='utf-8') as file:
            file.write(result.text)  # 读取爬到网页的源代码
    result.close()


# 03. 重新覆盖源文件
def write_file(source_file_param, page_text_param):
    with open(source_file_param, mode='w', encoding='utf-8') as file:
        file.write(page_text_param)  # 读取爬到网页的源代码


if __name__ == '__main__':
    # 读取文件
    page_text = read_file(source_file, file_save_path, file_access_path)
    # 写文件
    write_file(source_file, page_text)
